﻿'use client';

import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Input, 
  Select, 
  Space, 
  Modal, 
  Form, 
  message, 
  Card, 
  Tag, 
  Popconfirm,
  DatePicker,
  Row,
  Col
} from 'antd';
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, ExportOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { request } from '@/utils/request';
import AdminLayout from '@/components/AdminLayout';

const { RangePicker } = DatePicker;
const { Option } = Select;

interface User {
  id: number;
  username: string;
  email: string;
  phone: string;
  userType: string;
  status: string;
  realName: string;
  companyName: string;
  createdAt: string;
  lastLoginTime: string;
}

interface QueryParams {
  username?: string;
  email?: string;
  userType?: string;
  status?: string;
  startDate?: string;
  endDate?: string;
  page: number;
  size: number;
}

const UsersPage: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [queryParams, setQueryParams] = useState<QueryParams>({
    page: 1,
    size: 10
  });
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [form] = Form.useForm();

  // 获取用户列表
  const fetchUsers = async () => {
    setLoading(true);
    try {
      const response = await request.post('/admin/users/query', queryParams);
      
      if (response.code === 200) {
        setUsers(response.data.content);
        setTotal(response.data.totalElements);
      } else {
        message.error('获取用户列表失败: ' + response.message);
      }
    } catch (error) {
      console.error('获取用户列表错误:', error);
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, [queryParams]);

  // 搜索处理
  const handleSearch = (values: any) => {
    const searchParams = {
      ...queryParams,
      ...values,
      page: 1
    };
    
    if (values.dateRange && values.dateRange.length === 2) {
      searchParams.startDate = values.dateRange[0].format('YYYY-MM-DD');
      searchParams.endDate = values.dateRange[1].format('YYYY-MM-DD');
    }
    
    delete searchParams.dateRange;
    setQueryParams(searchParams);
  };

  // 重置搜索
  const handleReset = () => {
    setQueryParams({
      page: 1,
      size: 10
    });
    form.resetFields();
  };

  // 更新用户状态
  const handleStatusChange = async (userId: number, status: string) => {
    try {
      const response = await request.put(`/admin/users/${userId}/status`, { status });
      
      if (response.code === 200) {
        message.success('用户状态更新成功');
        fetchUsers();
      } else {
        message.error('用户状态更新失败: ' + response.message);
      }
    } catch (error) {
      console.error('更新用户状态错误:', error);
      message.error('用户状态更新失败');
    }
  };

  // 导出用户数据
  const handleExport = async () => {
    try {
      const response = await request.post('/admin/users/export', queryParams);
      
      if (response.code === 200) {
        message.success('导出成功');
        // TODO: 处理文件下载
      } else {
        message.error('导出失败: ' + response.message);
      }
    } catch (error) {
      console.error('导出错误:', error);
      message.error('导出失败');
    }
  };
  const handleResetPassword = async (userId: number) => {
    try {
      const response = await request.put(`/admin/users/${userId}/reset-password`);
      
      if (response.code === 200) {
        Modal.success({
          title: '密码重置成功',
          content: `新密码：${response.data.newPassword}`,
        });
      } else {
        message.error('密码重置失败: ' + response.message);
      }
    } catch (error) {
      console.error('重置密码错误:', error);
      message.error('密码重置失败');
    }
  };

  // 编辑用户
  const handleEdit = (user: User) => {
    setEditingUser(user);
    form.setFieldsValue(user);
    setIsModalVisible(true);
  };

  // 保存用户
  const handleSave = async (values: any) => {
    try {
      let response;
      
      if (editingUser) {
        // 更新用户
        response = await request.put(`/admin/users/${editingUser.id}`, values);
      } else {
        // 创建用户
        response = await request.post('/admin/users', values);
      }
      
      if (response.code === 200) {
        message.success(editingUser ? '用户更新成功' : '用户创建成功');
        setIsModalVisible(false);
        setEditingUser(null);
        form.resetFields();
        fetchUsers();
      } else {
        message.error((editingUser ? '用户更新失败' : '用户创建失败') + ': ' + response.message);
      }
    } catch (error) {
      console.error('保存用户错误:', error);
      message.error(editingUser ? '用户更新失败' : '用户创建失败');
    }
  };

  // 表格列定义
  const columns: ColumnsType<User> = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 120,
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      key: 'realName',
      width: 100,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 180,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 120,
    },
    {
      title: '用户类型',
      dataIndex: 'userType',
      key: 'userType',
      width: 100,
      render: (userType: string) => {
        const typeMap: Record<string, { color: string; text: string }> = {
          INDIVIDUAL: { color: 'blue', text: '个人用户' },
          ENTERPRISE: { color: 'green', text: '企业用户' },
          ADMIN: { color: 'red', text: '管理员' }
        };
        const type = typeMap[userType] || { color: 'default', text: userType };
        return <Tag color={type.color}>{type.text}</Tag>;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string, record: User) => {
        return (
          <Select
            value={status}
            style={{ width: 80 }}
            size="small"
            onChange={(value) => handleStatusChange(record.id, value)}
          >
            <Option value="ACTIVE">
              <Tag color="success">正常</Tag>
            </Option>
            <Option value="INACTIVE">
              <Tag color="default">禁用</Tag>
            </Option>
            <Option value="PENDING">
              <Tag color="warning">待审核</Tag>
            </Option>
          </Select>
        );
      },
    },
    {
      title: '公司名称',
      dataIndex: 'companyName',
      key: 'companyName',
      width: 150,
    },
    {
      title: '注册时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 160,
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginTime',
      key: 'lastLoginTime',
      width: 160,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要重置该用户的密码吗？"
            onConfirm={() => handleResetPassword(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" size="small">
              重置密码
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <AdminLayout 
      selectedKey="3" 
      breadcrumbItems={[{ title: '用户管理' }]}
    >
      <div style={{ padding: '24px' }}>
        <h1 style={{ marginBottom: '24px', fontSize: '24px', fontWeight: 'bold' }}>
          用户管理
        </h1>
        {/* 搜索表单 */}
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 16 }}
        >
          <Row gutter={16} style={{ width: '100%' }}>
            <Col span={6}>
              <Form.Item name="username">
                <Input placeholder="用户名" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="email">
                <Input placeholder="邮箱" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="userType">
                <Select placeholder="用户类型" allowClear>
                  <Option value="INDIVIDUAL">个人用户</Option>
                  <Option value="ENTERPRISE">企业用户</Option>
                  <Option value="ADMIN">管理员</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="status">
                <Select placeholder="状态" allowClear>
                  <Option value="ACTIVE">正常</Option>
                  <Option value="INACTIVE">禁用</Option>
                  <Option value="PENDING">待审核</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Space>
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                  搜索
                </Button>
                <Button onClick={handleReset}>
                  重置
                </Button>
              </Space>
            </Col>
          </Row>
        </Form>

        {/* 操作按钮 */}
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                setEditingUser(null);
                form.resetFields();
                setIsModalVisible(true);
              }}
            >
              新增用户
            </Button>
            <Button
              icon={<ExportOutlined />}
              onClick={handleExport}
            >
              导出数据
            </Button>
          </Space>
        </div>

        {/* 用户表格 */}
        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1300 }}
          pagination={{
            current: queryParams.page,
            pageSize: queryParams.size,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
            onChange: (page, size) => {
              setQueryParams(prev => ({ ...prev, page, size }));
            },
          }}
        />

        {/* 编辑/新增用户模态框 */}
        <Modal
          title={editingUser ? '编辑用户' : '新增用户'}
          open={isModalVisible}
          onCancel={() => {
            setIsModalVisible(false);
            setEditingUser(null);
            form.resetFields();
          }}
          footer={null}
          width={600}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSave}
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="username"
                  label="用户名"
                  rules={[{ required: true, message: '请输入用户名' }]}
                >
                  <Input placeholder="请输入用户名" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="realName"
                  label="真实姓名"
                  rules={[{ required: true, message: '请输入真实姓名' }]}
                >
                  <Input placeholder="请输入真实姓名" />
                </Form.Item>
              </Col>
            </Row>
            
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="email"
                  label="邮箱"
                  rules={[
                    { required: true, message: '请输入邮箱' },
                    { type: 'email', message: '请输入正确的邮箱格式' }
                  ]}
                >
                  <Input placeholder="请输入邮箱" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="phone"
                  label="手机号"
                  rules={[{ required: true, message: '请输入手机号' }]}
                >
                  <Input placeholder="请输入手机号" />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="userType"
                  label="用户类型"
                  rules={[{ required: true, message: '请选择用户类型' }]}
                >
                  <Select placeholder="请选择用户类型">
                    <Option value="INDIVIDUAL">个人用户</Option>
                    <Option value="ENTERPRISE">企业用户</Option>
                    <Option value="ADMIN">管理员</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="status"
                  label="状态"
                  rules={[{ required: true, message: '请选择状态' }]}
                >
                  <Select placeholder="请选择状态">
                    <Option value="ACTIVE">正常</Option>
                    <Option value="INACTIVE">禁用</Option>
                    <Option value="PENDING">待审核</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>

            <Form.Item
              name="companyName"
              label="公司名称"
            >
              <Input placeholder="请输入公司名称" />
            </Form.Item>

            {!editingUser && (
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    name="password"
                    label="密码"
                    rules={[{ required: true, message: '请输入密码' }]}
                  >
                    <Input.Password placeholder="请输入密码" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="confirmPassword"
                    label="确认密码"
                    rules={[
                      { required: true, message: '请确认密码' },
                      ({ getFieldValue }) => ({
                        validator(_, value) {
                          if (!value || getFieldValue('password') === value) {
                            return Promise.resolve();
                          }
                          return Promise.reject(new Error('两次输入的密码不一致'));
                        },
                      }),
                    ]}
                  >
                    <Input.Password placeholder="请确认密码" />
                  </Form.Item>
                </Col>
              </Row>
            )}

            <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
              <Space>
                <Button onClick={() => {
                  setIsModalVisible(false);
                  setEditingUser(null);
                  form.resetFields();
                }}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  {editingUser ? '更新' : '创建'}
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </AdminLayout>
  );
};

export default UsersPage;